<template>
  <div>
    <router-view>
      <div>
        <div style="height: 2vh;"></div>
        <el-card class="box-card">
          <template #header>
            <div style="font-size: 20px; font-weight: 600;">
              <span>医院信息</span>
            </div>
          </template>
          <div>
            <el-table ref="multipleTableRef" style="width: 100%" stripe :data="tableData" v-loading="loading"
              max-height="68vh">
              <el-table-column label="医院名称" property="name" width="210" align="center" fixed />
              <el-table-column property="type" label="医院类型" width="220" align="center" />
              <el-table-column property="tel" label="联系电话" show-overflow-tooltip width="180" align="center" />
              <!-- <el-table-column property="content" label="医院介绍" align="center">
                <template #default="scope">
                  <el-tooltip class="box-item" effect="dark" :content="contents" placement="top">
                    <div v-html="scope.row.content" class="column"></div>
                  </el-tooltip>
                </template>
              </el-table-column> -->
              <el-table-column property="address" label="医院地址" show-overflow-tooltip width="350" align="center" />
              <el-table-column property="create_time" label="医院图片" show-overflow-tooltip width="240" align="center">
                <template #default="scope">
                  <el-image :src="url + scope.row.profile" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                    :preview-src-list="[url + scope.row.profile]" fit="cover" preview-teleported="true"
                    style="width: 75px; height: 75px;" />
                </template>
              </el-table-column>
              <el-table-column property="create_time" label="创建时间" show-overflow-tooltip width="210" align="center" />
              <el-table-column fixed="right" label="操作" width="120" align="center">
                <template #default="scope">
                  <div style="display: flex; align-items: center;justify-content: center;">
                    <el-button type="success" plain size="small" @click="targets(scope.row.id, scope.row)">编辑</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

        </el-card>
        <el-dialog v-model="centerDialogVisibles" z-index="1000" title="信息编辑" width="50%" align-center
          :close-on-press-escape="false" :close-on-click-modal="false" :show-close="false">
          <div>
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="90px" class="demo-ruleForm"
              :size="formSize" status-icon>
              <el-form-item label="医院名称" prop="yyname">
                <el-input v-model="ruleForm.yyname" placeholder="请输入医院名称" />
              </el-form-item>
              <el-form-item label="联系电话" prop="tel">
                <el-input v-model="ruleForm.tel" placeholder="请输入联系电话" />
              </el-form-item>
              <el-form-item label="医院类型" prop="type">
                <el-input v-model="ruleForm.type" placeholder="请输入医院类型" />
              </el-form-item>
              <el-form-item label="医院地址" prop="address">
                <el-input v-model="ruleForm.address" placeholder="选择地图标点自动填充" readonly />
              </el-form-item>
              <div style="display: flex">
                <el-form-item label="经度" prop="lng">
                  <el-input v-model="ruleForm.lng" placeholder="选择地图标点自动填充" readonly />
                </el-form-item>
                <el-form-item label="纬度" prop="lat">
                  <el-input v-model="ruleForm.lat" placeholder="选择地图标点自动填充" readonly />
                </el-form-item>
              </div>
              <el-form-item label="地图">
                <div id="container"></div>
              </el-form-item>
              <el-form-item label="医院头像" prop="imageUrl">
                <el-upload class="avatar-uploader" action="https://lxt.jingyi.icu/pc/Fileimg/file" :show-file-list="false"
                  :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                  <img v-if="ruleForm.imageUrl" :src="url + ruleForm.imageUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>
              <el-form-item label="科室分布" prop="fileList">
                <el-upload v-model:file-list="ruleForm.fileList" action="https://lxt.jingyi.icu/pc/Fileimg/file"
                  list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                  :before-upload="handleBeforeUpload" :limit="1" :on-success="handleAvatar">
                  <img v-if="imageUrls" :src="imageUrls" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>
              <el-form-item label="医院介绍" prop="details">
                <vue-ueditor-wrap v-model="ruleForm.details" :config="editorConfig"
                  style="width: 87%;"></vue-ueditor-wrap>
              </el-form-item>
              <div style="direction: rtl;">
                <el-form-item>
                  <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确认
                  </el-button>
                  <div style="height: 10px;width: 10px;"></div>
                  <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </el-dialog>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: auto;height: auto;" />
        </el-dialog>
      </div>
    </router-view>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { Yyinfo } from '@/api/user'
import { hospital } from '@/api/doctor'

import { Plus } from '@element-plus/icons-vue'
import AMapLoader from '@amap/amap-jsapi-loader';
window._AMapSecurityConfig = {
  securityJsCode: '3eb550cdd88e45dd84d6babc8f3a99ab',
}
const tableData = ref([])
const loading = ref(true)
const url = ref('https://lxt.jingyi.icu')
const contents = ref('')
const ruleFormRef = ref('');
const centerDialogVisibles = ref(false)
// const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// const imageUrl = ref('')
const editorConfig = reactive({
  autoHeightEnabled: false,
  initialFrameHeight: 200,
  initialFrameWidth: '100%',
  UEDITOR_HOME_URL: '/ueditor/', // 访问 UEditor 静态资源的根路径publc里面的名称
  serverUrl: '/pc/pc/Fileimg/uderto', // 服务端接⼝
  uploadUrl: '/pc/pc/Fileimg/uderto' + '/kjyl-server-doctor/doctor/file/uploadFile',
  // enableAutoSave: true, // 开启从草稿箱恢复功能需要⼿动设置固定的 editorId，否则组件会默认随机⼀个，如果页⾯刷新，下次渲染的时候 editorId 会重新随机，
});
const editid = ref('')
const ruleForm = ref(
  {
    yyname: '',
    tel: '',
    type: '',
    lng: '',
    lat: '',
    address: '',
    details: '',
    imageUrl: '',
    fileList: []
  }
)
const rules = {
  yyname: [
    {
      required: true,
      message: '请输入医院名称',
      trigger: 'change'
    },
  ],
  tel: [
    {
      required: true,
      message: '请输入医院联系电话',
      trigger: 'change',
    },
  ],
  type: [
    {
      required: true,
      message: '请输入医院类型',
      trigger: 'change',
    },
  ],
  lng: [
    {
      required: true,
      message: '请输入经度',
      trigger: 'change',
    },
  ],
  lat: [
    {
      required: true,
      message: '请输入纬度',
      trigger: 'change',
    },
  ],
  address: [
    {
      required: true,
      message: '请输入医院地址',
      trigger: 'change',
    },
  ],
  details: [
    {
      required: true,
      message: '请输入医院介绍',
      trigger: 'change',
    },
  ],
  imageUrl: [
    {
      required: true,
      message: '请上传医院头像',
      trigger: 'change',
    },
  ],
  fileList: [
    {
      required: true,
      message: '请上传科室分布',
      trigger: 'change',
    },
  ],
};
payment()
function payment() {
  hospital().then((res) => {
    console.log(res);
    tableData.value = res.data;
    loading.value = false
    if (tableData.value) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(tableData.value[0].content, 'text/html');
      const textContent = doc.body.innerText;
      // console.log(textContent);
      contents.value = textContent
    }
  })
}

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log(ruleForm.value.fileList.url);
      console.log('submit!', ruleForm);
      Yyinfo({
        id: editid.value,
        content: ruleForm.value.details,
        name: ruleForm.value.yyname,
        lng: ruleForm.value.lng,
        lat: ruleForm.value.lat,
        tel: ruleForm.value.tel,
        address: ruleForm.value.address,
        avatar: ruleForm.value.imageUrl,
        type: ruleForm.value.type,
        profile: ruleForm.value.fileList[0].url.replace('https://lxt.jingyi.icu', '')
      }).then((res) => {
        
      // console.log(ruleForm.value.fileList[0].url.replace('http://lxt.jingyi.icu', ''),999999999);
        console.log(res);
        if (res.code == 1) {
          ElMessage({
            type: 'success',
            message: '编辑成功',

          });
          centerDialogVisibles.value = false

          payment()
        } else {
          ElMessage({
            type: 'error',
            message: '编辑失败',
          });
        }
      })
    } else {
      console.log('error submit!', fields);
    }
  });
};


const targets = (id, row) => {
  editid.value = id
  centerDialogVisibles.value = true
  initMap(row.lng, row.lat);
  ruleForm.value = (
    {
      yyname: row.name,
      tel: row.tel,
      type: row.type,
      lng: row.lng,
      lat: row.lat,
      address: row.address,
      details: row.content,
      imageUrl: row.avatar,
      fileList: [{
        url: url.value + row.profile
      }]
    }
  )
}
const initMap = (lng, lat) => {
  AMapLoader.load({
    key: '11b9b0045f8bc94b504861e860d3d359',
    version: '1.4.4',
    plugins: ['AMap.Marker', 'AMap.Geocoder'], // 添加地理编码插件
  }).then((AMap) => {
    const map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 9.5,
      center: [lng, lat],
    });
    const marker = new AMap.Marker({
      position: [lng, lat],
      map: map,
    });
    const geocoder = new AMap.Geocoder({}); // 创建地理编码实例

    map.on('click', (e) => {
      geocoder.getAddress(e.lnglat, function (status, result) {
        console.log(status, result);
        if (status === 'complete' && result.regeocode) {
          const address = result.regeocode.formattedAddress;
          console.log(address);
          ruleForm.value.address = address;
          const infoWindowContent = `经度：${e.lnglat.lng}<br>纬度：${e.lnglat.lat}<br>地址：${address}`;
          const infoWindow = new AMap.InfoWindow({
            content: infoWindowContent,
            offset: new AMap.Pixel(0, -30), // 设置信息窗体偏移量，使其在标记上方
          });
          infoWindow.open(map, e.lnglat); // 在地图上打开信息窗体
        }
      });
      ruleForm.value.lng = e.lnglat.lng;
      ruleForm.value.lat = e.lnglat.lat;
      marker.setPosition(e.lnglat);
    });
  });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  ruleForm.value = (
    {
      yyname: '',
      tel: '',
      type: '',
      lng: '',
      lat: '',
      address: '',
      details: '',
      imageUrl: '',
      fileList: []
    }
  )
  setTimeout(() => {
    formEl.clearValidate();
  }, 20)

  centerDialogVisibles.value = false
  initMap(116.407387, 39.904179)
};

const handleRemove = (file, fileList) => {
  console.log(file, fileList);
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

const handleBeforeUpload = (file) => {
  console.log(file);
  console.log(ruleForm.value.fileList);
  file.headers = {
    id: JSON.parse(localStorage.getItem('data')).data.id
  };
  return true;
};
const handleAvatarSuccess = (response, uploadFile) => {
  console.log(response);
  ruleForm.value.imageUrl = response.data.url;
};
const handleAvatar = (resp, upload) => {
  ruleForm.value.fileList = ({
    url: url.value + resp.data.url
  });
}
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('大小不能超过2MB');
    return false;
  }
  return true;
};
</script>
<style>
.column {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 6;
  overflow: hidden;
  text-overflow: ellipsis;
  word-wrap: break-word;
}

#container {
  width: 100%;
  height: 300px;
}

.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #FAFAFA;

  transition: var(--el-transition-duration-fast);

}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}

.el-dialog__body {
  padding: calc(var(--el-dialog-padding-primary) + 10px) var(--el-dialog-padding-primary);
  color: var(--el-text-color-regular);
  font-size: var(--el-dialog-content-font-size);
  word-break: break-all;
  text-align: center !important;
}
</style>